package com.njupt.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/12/18 8:42
 * @Description: 47. 全排列 II
 * @Version: 1.0
 */


public class PermuteUnique_47 {

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        traceBacking(nums,used,results,path);
        return results;

    }

    private void traceBacking(int[] nums, boolean[] used, List<List<Integer>> results, List<Integer> path) {
        if(path.size() == nums.length){
            results.add(new ArrayList(path));
            return;
        }

        for (int i = 0; i < used.length; i++) {
            if(used[i] == true || i>0 && (nums[i] == nums[i-1] && used[i-1] == false)){
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            traceBacking(nums,used,results,path);
            used[i] = false;
            path.remove(path.size()-1);

        }

    }

    public static void main(String[] args) {
        int[] nums = {3,3,0,3};
        PermuteUnique_47 test = new PermuteUnique_47();
        List<List<Integer>> results = test.permuteUnique(nums);
        System.out.println(results);

    }
}
